<template>
  <!-- 变更报价 -->
  <a-modal :width="1000" v-model:visible="showChangePrice" title="变更报价" top="8vh" title-align="start" :on-before-ok="submitData" :ok-loading="submitLoading" :mask-closable="false" @cancel="closedDialog">
    <p style="margin-bottom: 5px">变更单需经过供应商和经销商双方同意之后方可生效；</p>
    <a-form ref="formRef" :model="formInfo" :rules="rules">
      <a-row>
        <a-col :span="24">
          <a-form-item hide-label>
            <a-textarea v-model="formInfo.remark" placeholder="变更原因" allow-clear />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="8">
          <a-form-item field="moq" label="最小起订量：" label-col-flex="100px">
            <a-input-number v-model="formInfo.moq" :precision="0" placeholder="" :min="0" />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item field="currency" label="币种：" label-col-flex="100px">
            <a-select v-model="formInfo.currency" placeholder="" allow-search>
              <a-option :value="item" :label="item" v-for="(item, i) in Object.keys(currencySymbol)" :key="i" />
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item field="invoiceType" label="发票类型：" label-col-flex="100px">
            <a-select v-model="formInfo.invoiceType" placeholder="">
              <a-option :value="1" label="普票" />
              <a-option :value="2" label="专票" />
              <a-option :value="0" label="不开票" />
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="8">
          <a-form-item field="parTaxRate" label="票面税率：" label-col-flex="100px">
            <a-input-number v-model="formInfo.parTaxRate" :precision="0" @change="changeParTaxRate" placeholder="" :min="0" />
            <span style="margin-left: 5px">%</span>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item field="refundTaxRate" label="退税率：" label-col-flex="100px">
            <a-input-number v-model="formInfo.refundTaxRate" :precision="0" placeholder="" :min="0" />
            <span style="margin-left: 5px">%</span>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item field="deliveryDays" label="交期：" label-col-flex="100px">
            <a-input-number v-model="formInfo.deliveryDays" :precision="0" placeholder="" :min="0" />
            <span style="margin-left: 5px">天</span>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24">
          <a-form-item hide-label>
            <a-radio-group v-model="formInfo.quoteType">
              <a-radio :value="1">非梯度报价</a-radio>
              <a-radio :value="2">梯度报价</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
      </a-row>
      <div class="price-w">
        <a-row v-if="formInfo.quoteType === 1">
          <a-col :span="7">
            <a-form-item field="priceInfo.price" label="不含税单价：" label-col-flex="100px">
              <span style="margin-right: 5px">{{ currencySymbol[formInfo.currency] || '￥' }}</span>
              <a-input-number v-model="formInfo.priceInfo.price" @change="changePrice(formInfo.priceInfo, 'price')" :precision="2" placeholder="" :min="0" />
            </a-form-item>
          </a-col>
          <a-col :span="5">
            <a-form-item label="税额：" label-col-flex="100px">
              <span style="margin-right: 5px">{{ currencySymbol[formInfo.currency] || '￥' }}</span>
              <span>{{ ((Number(formInfo.priceInfo.price || 0) * Number(formInfo.parTaxRate || 0)) / 100).toFixed(2) }}</span>
            </a-form-item>
          </a-col>
          <a-col :span="7">
            <a-form-item field="priceInfo.taxPrice" label="含税单价：" label-col-flex="100px">
              <span style="margin-right: 5px">{{ currencySymbol[formInfo.currency] || '￥' }}</span>
              <a-input-number v-model="formInfo.priceInfo.taxPrice" :precision="2" placeholder="" @change="changePrice(formInfo.priceInfo, 'taxPrice')" :min="0" />
            </a-form-item>
          </a-col>
          <a-col :span="5">
            <a-form-item label="可退税额：" label-col-flex="100px">
              <span style="margin-right: 5px">{{ currencySymbol[formInfo.currency] || '￥' }}</span>
              <span>{{ ((Number(formInfo.priceInfo.price || 0) * Number(formInfo.refundTaxRate || 0)) / 100).toFixed(2) }}</span>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row v-else>
          <a-col :span="24">
            <a-table class="table-singe-line" ref="tableRef" row-key="id" :data="formInfo.quoteItems" size="mini" :bordered="false" :pagination="false">
              <template #columns>
                <a-table-column :width="120">
                  <template #title>
                    <p>
                      <span class="warningColor">*</span>
                      <span>数量</span>
                    </p>
                  </template>
                  <template #cell="{ record, rowIndex }">
                    <a-form-item :field="rowIndex + 'quantity'" hide-label style="margin-bottom: 0">
                      <span style="margin-right: 5px">>=</span>
                      <a-input-number v-model="record.quantity" style="width: 100px" :precision="0" placeholder="请输入" :min="0" />
                    </a-form-item>
                  </template>
                </a-table-column>
                <a-table-column :width="120">
                  <template #title>
                    <p>
                      <span class="warningColor">*</span>
                      <span>不含税单价</span>
                    </p>
                  </template>
                  <template #cell="{ record, rowIndex }">
                    <a-form-item :field="rowIndex + 'price'" hide-label style="margin-bottom: 0">
                      <span style="margin-right: 5px">{{ currencySymbol[formInfo.currency] || '￥' }}</span>
                      <a-input-number v-model="record.price" style="width: 100px" @change="changePrice(record, 'price')" :precision="2" placeholder="请输入" :min="0" />
                    </a-form-item>
                  </template>
                </a-table-column>
                <a-table-column title="税额" :width="100">
                  <template #cell="{ record }">
                    <span style="margin-right: 5px">{{ currencySymbol[formInfo.currency] || '￥' }}</span>
                    <span>{{ ((Number(record.price || 0) * Number(formInfo.parTaxRate || 0)) / 100).toFixed(2) }}</span>
                  </template>
                </a-table-column>
                <a-table-column :width="120">
                  <template #title>
                    <p>
                      <span class="warningColor">*</span>
                      <span>含税单价</span>
                    </p>
                  </template>
                  <template #cell="{ record, rowIndex }">
                    <a-form-item :field="rowIndex + 'taxPrice'" hide-label style="margin-bottom: 0">
                      <span style="margin-right: 5px">{{ currencySymbol[formInfo.currency] || '￥' }}</span>
                      <a-input-number v-model="record.taxPrice" style="width: 100px" @change="changePrice(record, 'taxPrice')" :precision="2" placeholder="请输入" :min="0" />
                    </a-form-item>
                  </template>
                </a-table-column>
                <a-table-column title="可退税额" :width="100">
                  <template #cell="{ record }">
                    <span style="margin-right: 5px">{{ currencySymbol[formInfo.currency] || '￥' }}</span>
                    <span>{{ ((Number(record.price || 0) * Number(formInfo.refundTaxRate || 0)) / 100).toFixed(2) }}</span>
                  </template>
                </a-table-column>
                <a-table-column title="操作" :width="100">
                  <template #cell="{ rowIndex }">
                    <a-space>
                      <a-button type="text" @click="formInfo.quoteItems.splice(rowIndex + 1, 0, {})">添加</a-button>
                      <a-button type="text" v-if="formInfo.quoteItems.length > 1" @click="formInfo.quoteItems.splice(rowIndex, 1)">移除</a-button>
                    </a-space>
                  </template>
                </a-table-column>
              </template>
            </a-table>
          </a-col>
        </a-row>
      </div>
    </a-form>
  </a-modal>
</template>
<script lang="ts" setup>
  import { ref, onMounted } from 'vue'
  import { changePurchaseQuote } from '@/api/purchase'
  import { currencySymbol } from '@/utils/globalData'
  import { Message } from '@arco-design/web-vue'
  onMounted(() => {
    setDefaultData()
  })
  const emit = defineEmits(['closed', 'success'])
  const props = defineProps({
    isShow: {
      type: Boolean,
      default: false,
    },
    currentItem: {
      type: Object,
      default: () => {},
    },
  })
  const rules = ref({
    deliveryDays: [{ required: true, message: '请输入交期' }],
    moq: [{ required: true, message: '请输入最小起订量' }],
    currency: [{ required: true, message: '请选择货币' }],
    invoiceType: [{ required: true, message: '请选择发票类型' }],
    parTaxRate: [{ required: true, message: '请输入票面税率' }],
    refundTaxRate: [{ required: true, message: '请输入退税率' }],
    'priceInfo.price': [{ required: true, message: '请输入不含税单价' }],
    'priceInfo.taxPrice': [{ required: true, message: '请输入含税单价' }],
  })

  const showChangePrice = ref(props.isShow)
  const formInfo = ref<any>({})
  const submitLoading = ref(false)
  const formRef = ref()

  // 修改单价关联
  function changePrice(item: any, key: string) {
    let parTaxRate = formInfo.value.parTaxRate || 0
    // 修改不含税单价
    if (key === 'price') {
      let val = Number(((item.price || 0) * (1 + parTaxRate / 100)).toFixed(2))
      item.taxPrice = val
    }
    // 修改含税单价
    if (key === 'taxPrice') {
      let val = Number(((item.taxPrice || 0) / (1 + parTaxRate / 100)).toFixed(2))
      item.price = val
    }
  }
  function changeParTaxRate() {
    changePrice(formInfo.value.priceInfo, 'price')
    formInfo.value.quoteItems.forEach((el: any) => {
      changePrice(el, 'price')
    })
  }
  // 添加初始化数据
  function setDefaultData() {
    formInfo.value = JSON.parse(JSON.stringify(props.currentItem))
    formInfo.value.priceInfo = {}
    // 非梯度报价
    if (formInfo.value.quoteType === 1) {
      formInfo.value.priceInfo = formInfo.value.quoteItems?.[0] || {}
    }
  }
  // 关闭
  function closedDialog() {
    emit('closed')
  }
  // 校验
  async function validInfo() {
    let valid = await formRef.value.validate((valid: any) => {
      return valid
    })
    if (valid) return false
    // 梯度报价的校验
    if (formInfo.value.quoteType === 2) {
      let rules = {}
      formInfo.value.quoteItems.forEach((el: any, i: number) => {
        let arr = ['quantity', 'price', 'taxPrice']
        arr.forEach((key: string) => {
          if (isNull(el[key])) {
            rules[i + key] = {
              status: 'error',
              message: '必填',
            }
          }
        })
      })
      formRef.value.setFields(rules)
      if (Object.keys(rules).length) return false
    }
    return true
  }
  function isNull(val: any) {
    return val === undefined || val === null || val === ''
  }
  // 保存信息
  async function submitData() {
    let valid = await validInfo()
    if (!valid) return false
    let params = JSON.parse(JSON.stringify(formInfo.value))
    params.changeType = 'quote'
    // 非梯度报价
    if (params.quoteType === 1) {
      params.quoteItems = [params.priceInfo]
    }
    delete params.priceInfo
    const res = await changePurchaseQuote({ changeItems: [params] })
    if (!res) return false
    Message.success('保存成功')
    emit('success')
    closedDialog()
  }
</script>
<style lang="less" scoped>
  .price-w {
    height: calc(84vh - 420px);
  }
</style>
